package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl implements RoleService {
        @Autowired
        private RoleMapper roleMapper;
        @Autowired
        private RoleResourceMapper roleResourceMapper;
        @Autowired
        private UserRoleMapper userRoleMapper;

    /**
     * 角色分页查询
     * @param pageNum
     * @param pageSize
     * @param roleDto
     * @return
     */
    @Override
    public PageResponse<RoleVo> getRoleList(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        if (pageNum == null || pageSize == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }
        PageHelper.startPage(pageNum,pageSize);
        //条件查询角色列表
        Page<RoleVo> page = roleMapper.selectRoleList(roleDto);
        //返回查询数据
        return PageResponse.of(page,RoleVo.class);
    }

    /**
     * 根据角色id查询关联的资源编号
     * @param roleId
     * @return
     */
    @Override
    public Set<String> getRoleResourceById(Long roleId) {
        if (roleId == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        //查询与角色关联的资源编号
        Set<String> resources = roleResourceMapper.selectResourceNoByRoleId(roleId);

        return resources;
    }

    /**
     * 添加角色
     */
    @Override
    public void addRole(RoleDto roleDto) {
        if (roleDto == null || roleDto.getRoleName() == null || roleDto.getDataState() == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //向角色表中添加新角色
        roleMapper.insertRole(role);
    }

    /**
     * 角色修改
     * @param roleDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(RoleDto roleDto) {
        if (roleDto == null || roleDto.getId() == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        //如果角色关联了用户，不能禁用
        if (roleDto.getDataState() != null && roleDto.getDataState().equals(SuperConstant.DATA_STATE_1)) { //表示要修改为禁用
            //查询绑定该角色的用户
            List<UserRole> userRoles = userRoleMapper.selectUserRoleByRoleId(roleDto.getId());
            //如果若该角色已绑定用户，不能禁用
            if (userRoles != null && userRoles.size() != 0) {
                throw new BaseException(BasicEnum.ROLE_DISABLE);
            }

        }

        Role role = BeanUtil.toBean(roleDto, Role.class);
        //更新角色信息
        roleMapper.updateRoleById(role);

        //更新角色关联的资源编号
        //如果资源编号数据不为空，则需要修改资源编号
        if (roleDto.getCheckedResourceNos() != null && roleDto.getCheckedResourceNos().length != 0) {

            //先删除原有关联的资源编号
            roleResourceMapper.deleteResourceByRoleId(roleDto.getId());

            //再重新添加资源编号到关联表中
            String[] resourceNos = roleDto.getCheckedResourceNos();

            //1、创建存储关联的角色资源对象集合
            List<RoleResource> roleResources = new ArrayList<>();
            for (String resourceNo : resourceNos) {
                //创建角色资源对象
                RoleResource roleResource = RoleResource.builder().roleId(roleDto.getId())
                        .dataState(SuperConstant.DATA_STATE_0).resourceNo(resourceNo).build();
                roleResources.add(roleResource);
            }

            //2、批量添加到关联表中
            roleResourceMapper.insertRoleResource(roleResources);
        }
    }

    /**
     * 删除角色
     * @param roleId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long roleId) {
        if (roleId == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        //根据角色id查询角色信息
        Role role = roleMapper.selectRoleById(roleId);
        //如果角色是启用状态不能删除
        if (role.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new BaseException(BasicEnum.MENU_ENABLE);
        }

        //查询判定该角色的用户
        List<UserRole> userRoles = userRoleMapper.selectUserRoleByRoleId(roleId);
        //如果若该角色已绑定用户，不能删除
        if (userRoles != null && userRoles.size() != 0) {
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED);
        }

        //删除角色
        roleMapper.deleteRoleById(roleId);
        //同时删除角色的关联的资源编号信息
        roleResourceMapper.deleteResourceByRoleId(roleId);
    }


    /**
     * 查询全部角色
     * @return
     */
    @Override
    public List<Role> getAllRole() {

        //查询全部角色
        List<Role> roles = roleMapper.selectAllRole();

        return roles;
    }
}
